# -*- coding: utf-8 -*-
import json
import logging

from datetime import timedelta

from utils.tz import get_utc_date, local_now
from utils.cache import set_activity_switch, get_activity_switch
from settings import MG as mg


_LOGGER = logging.getLogger('bot')


LOTTERY_TYPE = {
    1: u"重庆时时彩",
    3: u"江苏快3",
    4: u"山东11选5",
    6: u"天津时时彩",
    7: u"新疆时时彩",
    8: u"江西11选5",
    9: u"广东11选5",
    10: u"上海11选5",
    11: u"广西快3",
    12: u"北京PK10"
}


class CmdParser(object):

    def __init__(self):
        pass
 
    def _cmd_user(self, the_date):
        day = the_date.strftime('%Y-%m-%d')
        item = mg.daily_report.find_one({'_id': day}) or {}
        new_user = item.get('new_user', 0)
        active_user = item.get('active_user', 0)
        day_2_ago = (the_date - timedelta(1)).strftime('%Y-%m-%d')
        item_2_ago = mg.daily_report.find_one({'_id': day_2_ago}) or {}
        user_stay_2 = item_2_ago.get('user_stay_2', 0)
        day_3_ago = (the_date - timedelta(3)).strftime('%Y-%m-%d')
        item_3_ago = mg.daily_report.find_one({'_id': day_3_ago}) or {}
        user_stay_3 = item_3_ago.get('user_stay_3', 0)
        day_7_ago = (the_date - timedelta(7)).strftime('%Y-%m-%d')
        item_7_ago = mg.daily_report.find_one({'_id': day_7_ago}) or {}
        user_stay_7 = item_7_ago.get('user_stay_7', 0)
        resp_msg = u'**注册**:{}\n'.format(new_user)
        resp_msg += u'**活跃**:{}\n'.format(active_user)
        resp_msg += u'**昨日留存**:{}\n'.format(user_stay_2)
        resp_msg += u'**3日留存**:{}\n'.format(user_stay_3)
        resp_msg += u'**7日留存**:{}\n'.format(user_stay_7)
        return resp_msg

    def cmd_today_user(self):
        today_date = local_now()
        return self._cmd_user(today_date)

    def cmd_yesterday_user(self):
        today_date = local_now() - timedelta(1)
        return self._cmd_user(today_date)

    def _cmd_bull(self, the_date):
        day = the_date.strftime('%Y-%m-%d')
        item = mg.bull_report.find_one({'_id': day}) or {}
        game_count = item.get('count', 0)
        user_count = item.get('real_user_count', 0)
        bet_amount = item.get('bet_amount', 0)
        bull_sys_bet_amount = item.get('sys_bet_amount', 0)
        bull_sys_award_amount = item.get('sys_award_amount', 0)
        bull_sys_profit = float(bull_sys_bet_amount - bull_sys_award_amount) / bull_sys_bet_amount
        bull_sys_profit = bull_sys_profit * 100
        _LOGGER.info('bull sys profit:%s', bull_sys_profit)
        user_gain = item.get('gain_amount', 0) + item.get('lose_amount', 0)
        resp_msg = u'**百人牛牛局数**:{}\n'.format(game_count)
        resp_msg += u'**百人牛牛人数**:{}\n'.format(user_count)
        resp_msg += u'**百人牛牛下注**:{}\n'.format(bet_amount)
        resp_msg += u'**百人牛牛抽成**:%.2f%%\n' % bull_sys_profit
        resp_msg += u'**百人牛牛用户盈利**:{}\n'.format(user_gain)
        return resp_msg

    def cmd_today_bull(self):
        today_date = local_now()
        return self._cmd_bull(today_date)

    def cmd_yesterday_bull(self):
        date = local_now() - timedelta(1)
        return self._cmd_bull(date)

    def _cmd_lottery(self, the_date):
        day = the_date.strftime('%Y-%m-%d')
        item = mg.lottery_report.find_one({'_id': day}) or {}
        game_count = item.get('count', 0)
        user_count = item.get('real_user_count', 0)
        bet_amount = item.get('bet_amount', 0)
        choucheng = item.get('profit_rate', 0) * 100
        user_gain = item.get('gain_amount', 0) + item.get('lose_amount', 0)
        resp_msg = u'**转转转局数**:{}\n'.format(game_count)
        resp_msg += u'**转转转人数**:{}\n'.format(user_count)
        resp_msg += u'**转转转下注**:{}\n'.format(bet_amount)
        resp_msg += u'**转转转抽成**:%.2f%%\n' % choucheng
        resp_msg += u'**转转转用户盈利**:{}\n'.format(user_gain)
        return resp_msg

    def cmd_today_lottery(self):
        today_date = local_now()
        return self._cmd_lottery(today_date)

    def cmd_yesterday_lottery(self):
        date = local_now() - timedelta(1)
        return self._cmd_lottery(date)

    def _cmd_slots(self, the_date):
        day = the_date.strftime('%Y-%m-%d')
        item = mg.kfc_report.find_one({'_id': day}) or {}
        user_count = item.get('real_user_count', 0)
        user_bet = item.get('bet_amount', 0)
        choucheng = item.get('profit_rate', 0) * 100
        user_gain = item.get('gain_amount', 0) + item.get('lose_amount', 0)
        resp_msg = u'**slots人数**:{}\n'.format(user_count)
        resp_msg += u'**slots下注**:{}\n'.format(user_bet)
        resp_msg += u'**slots抽成**:%.2f%%\n' % choucheng
        resp_msg += u'**slots用户盈利**:{}\n'.format(user_gain)
        return resp_msg

    def cmd_today_slots(self):
        today_date = local_now()
        return self._cmd_slots(today_date)

    def cmd_yesterday_slots(self):
        date = local_now() - timedelta(1)
        return self._cmd_slots(date)

    def _cmd_fruit(self, the_date):
        day = the_date.strftime('%Y-%m-%d')
        item = mg.fruit_report.find_one({'_id': day}) or {}
        game_count = item.get('count', 0)
        user_count = item.get('real_user_count', 0)
        bet_amount = item.get('bet_amount', 0)
        choucheng = item.get('profit_rate', 0) * 100
        user_gain = item.get('gain_amount', 0) + item.get('lose_amount', 0)
        resp_msg = u'**水果机局数**:{}\n'.format(game_count)
        resp_msg += u'**水果机人数**:{}\n'.format(user_count)
        resp_msg += u'**水果机下注**:{}\n'.format(bet_amount)
        resp_msg += u'**水果机抽成**:%.2f%%\n' % choucheng
        resp_msg += u'**水果机用户盈利**:{}\n'.format(user_gain)
        return resp_msg

    def cmd_today_fruit(self):
        today_date = local_now()
        return self._cmd_fruit(today_date)

    def cmd_yesterday_fruit(self):
        date = local_now() - timedelta(1)
        return self._cmd_fruit(date)

    def _cmd_recharge(self, the_date):
        day = the_date.strftime('%Y-%m-%d')
        item = mg.daily_report.find_one({'_id': day}) or {}
        recharge_price = item.get('recharge_price', 0)
        recharge_user = item.get('recharge_user', 0)
        new_recharge_price = item.get('new_recharge_price', 0)
        new_recharge_user = item.get('new_recharge_user', 0)
        withdraw_price = item.get('withdraw_price', 0)
        withdraw_user = item.get('withdraw_count', 0)
        resp_msg = u'**充值人数**:{}\n'.format(recharge_user)
        resp_msg += u'**充值金额**:{}\n'.format(recharge_price)
        resp_msg += u'**新增充值人数**:{}\n'.format(new_recharge_user)
        resp_msg += u'**新增充值金额**:{}\n'.format(new_recharge_price)
        resp_msg += u'**兑换人数**:{}\n'.format(withdraw_user)
        resp_msg += u'**兑换金额**:{}\n'.format(withdraw_price)
        return resp_msg

    def cmd_today_recharge(self):
        today_date = local_now()
        return self._cmd_recharge(today_date)

    def cmd_yesterday_recharge(self):
        date = local_now() - timedelta(1)
        return self._cmd_recharge(date)

    def _cmd_profit(self, the_date):
        day = the_date.strftime('%Y-%m-%d')
        item = mg.daily_report.find_one({'_id': day}) or {}
        profit = item.get('profit', 0)
        profit_rate = item.get('profit_rate', 0) * 100
        resp_msg = u'**营收**:{}\n'.format(profit)
        resp_msg += u'**利润率**:%.2f%%\n' % profit_rate
        return resp_msg

    def cmd_today_profit(self):
        today_date = local_now()
        return self._cmd_profit(today_date)

    def cmd_yesterday_profit(self):
        date = local_now() - timedelta(1)
        return self._cmd_profit(date)

    def _cmd_bigbang(self, the_date):
        day = the_date.strftime('%Y-%m-%d')
        resp_msg = ''
        for k, v in LOTTERY_TYPE.items():
            item = mg.activity_stats.find_one({
                '_id': '{}-{}'.format(k, day)
            })
            if not item:
                continue
            pay = item.get('pay', {}).get('total', 0)
            win = item.get('win', {}).get('total', 0)
            bonus = item.get('bonus', {}).get('total', 0)
            refund = item.get('refund', {}).get('total', 0)
            gain = pay - win - bonus - refund
            if pay > 0:
                profit_rate = float(gain) / pay
                resp_msg += u'**%s**:\n利润率%.2f%%\n购彩%s\n中奖%s\n加奖%s\n退款%s\n盈利%s\n' % (
                    v, profit_rate*100, pay, win, bonus, refund, gain)
            else:
                resp_msg += u'**%s**:\n购彩%s\n中奖%s\n加奖%s\n退款%s\n盈利%s\n' % (
                    v, pay, win, bonus, refund, gain)
        return resp_msg

    def cmd_today_bigbang(self):
        today_date = local_now()
        return self._cmd_bigbang(today_date)

    def cmd_yesterday_bigbang(self):
        date = local_now() - timedelta(1)
        return self._cmd_bigbang(date)

    def cmd_resp(self, cmd):
        if hasattr(self, cmd):
            func = getattr(self, cmd)
            return func()
        if cmd.startswith('cmd_switch_'):
            activity_type = int(cmd.split('_')[2] or 0)
            if activity_type in LOTTERY_TYPE:
                off = get_activity_switch(activity_type)
                if off:
                    # 开启
                    set_activity_switch(activity_type, 0)
                    resp_msg = u'您开启了{}'.format(LOTTERY_TYPE[activity_type])
                else:
                    # 关闭
                    set_activity_switch(activity_type, 1)
                    resp_msg = u'您关闭了{}'.format(LOTTERY_TYPE[activity_type])
                return resp_msg
                
        return u'指令无效'

    def match_text(self, text):
        if (u'今日充值' in text or u'今日流水' in text):
            return 'cmd_today_recharge'
        if (u'今日利润' in text or u'今日营收' in text):
            return 'cmd_today_profit'
        if (u'今日用户' in text or u'今日人' in text):
            return 'cmd_today_user'
        if (u'百人牛牛' in text):
            return 'cmd_today_bull'
        if (u'大转盘' in text or u'转转转' in text):
            return 'cmd_today_lottery'
        if (u'slots' in text or u'捉金鸡' in text):
            return 'cmd_today_slots'
        if (u'猜水果' in text or u'水果机' in text):
            return 'cmd_today_fruit'
        if (u'购彩' in text or u'bigbang' in text):
            return 'cmd_today_bigbang'
